package dparish.server.dao;

import java.util.List;

import com.google.web.bindery.requestfactory.shared.Locator;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;


import dparish.shared.entity.DatastoreObject;

/**
 * Common RequestFactory locator taking advantage of common DAO classes
 * @see <a href="http://turbomanage.wordpress.com/2011/03/25/using-gwt-requestfactory-with-objectify/">RequestFactory with Objectify</a>
 * 
 * also contains base DAO actions (store, findall, etc..
 *
 */
public abstract class GenericLocator<Entity extends DatastoreObject> extends Locator<DatastoreObject, Long>{

	public static final Objectify objectify = ObjectifyService.begin();
	
	@Override
	public DatastoreObject create(Class<? extends DatastoreObject> clazz) {
		try
		{
			return clazz.newInstance();
		} catch (InstantiationException e)
		{
		  throw new RuntimeException(e);
		} catch (IllegalAccessException e)
		{
			throw new RuntimeException(e);
		}
	}

	public GenericLocator() {
		
	}
	
	public abstract List<Entity> findAll();
	public abstract DatastoreObject find(Long id); 
	
	public void store (DatastoreObject entity) {
		objectify.put(entity);
	}
	
	public List<Entity> findAll (Class<Entity> clazz) {
		Query<Entity> query = objectify.query(clazz);
		return query.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Entity find(Class<? extends DatastoreObject> clazz, Long id) {
		return (Entity) objectify.find(clazz, id);
	}

	@Override
	public Class<DatastoreObject> getDomainType() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Long getId(DatastoreObject domainObject) {
		return domainObject.getId();
	}

	@Override
	public Class<Long> getIdType() {
		return Long.class;
	}

	@Override
	public Object getVersion(DatastoreObject domainObject) {
		return domainObject.getVersion();
	}

}
